package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.EventWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.LoanFilterProductAdapter;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.controller.CommonJumpController;
import com.cardbaobao.cardbabyclient.model.Banner;
import com.cardbaobao.cardbabyclient.model.LoanPopFilterList;
import com.cardbaobao.cardbabyclient.model.SpeedOrProduct;
import com.cardbaobao.cardbabyclient.model.result.BannerResult;
import com.cardbaobao.cardbabyclient.model.result.LoanPopFilterListResult;
import com.cardbaobao.cardbabyclient.model.result.SpeedOrProductResult;
import com.cardbaobao.cardbabyclient.ui.pop.LoanAmountPop;
import com.cardbaobao.cardbabyclient.ui.pop.LoanProfessionPop;
import com.cardbaobao.cardbabyclient.ui.pop.LoanSortPop;
import com.cardbaobao.cardbabyclient.ui.pop.LoanTypePop;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.LocationUtil;
import com.cardbaobao.cardbabyclient.utils.ScreenUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.cardbaobao.cardbabyclient.widget.refresh.FooterLoadMore;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.stx.xhb.xbanner.XBanner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 14:43.
 * 可按条件[身份、借款金额、借款类型、升降序排序]筛选的贷款
 */
public class LoanFilterActivity extends BaseActivity {
    private static final int PAGE_START = 1;//分页开始页码
    public static final int POP_PROFESSION = 1;//身份信息pop
    public static final int POP_AUTH_REPAYMENT = 2;//授权类型、还款方式pop
    public static final String LOAN_FILTER_PROFESSION_S = "loanProfessionType";//人群分类code
    public static final String LOAN_FILTER_PROFESSION_NAME_S = "loanTypeName";//人群分类名称
    public static final String LOAN_TYPE_AUTH_REPAYMENT_CODE_S = "";//授权方式、还款方式code
    public static final String LOAN_TYPE_AUTH_REPAYMENT_NAME_S = "loanTypeAuthName";//授权方式、还款方式名称
    public static final String LOAN_FILTER_AMOUNT_I = "loanAmount";//借款金额
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.main_appbar)
    AppBarLayout appBarLayout;
    @BindView(R.id.collapsing_toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R.id.xb_banner)
    XBanner xBanner;

    @BindView(R.id.ll_container)
    LinearLayout llContainer;//条件筛选容器

    @BindView(R.id.tv_identity)
    TextView tvIdentity;

    @BindView(R.id.tv_amount)
    TextView tvAmount;

    @BindView(R.id.tv_type)
    TextView tvType;

    private Drawable expansionDownDrawable;
    private Drawable expansionUpDrawable;
    private static final int COLOR_NORMAL = 0xff222222;
    private static final int COLOR_SELECTED = 0xffff9e27;

    @BindView(R.id.srLayout)
    SmartRefreshLayout srLayout;
    @BindView(R.id.footerLoadMore)
    FooterLoadMore footerLoadMore;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    private List<SpeedOrProduct.LoanListBean> data;
    private LoanFilterProductAdapter adapter;

    @BindView(R.id.rl_sort_filter)
    RelativeLayout rlSortFilter;

    private int pageNumber = PAGE_START;
    private String crowds_code = "";//人群分类
    private String codes = "";//授权方式，还款方式code
    private String order = "";
    private int amount = 0;

    private SpeedOrProductResult speedOrProductResult;
    private List<LoanPopFilterList.LoanPopFilter> loanPopFilters;//借款类型筛选条件
    private List<LoanPopFilterList.LoanPopFilter> repaymentFilters;//还款方式筛选条件

    private LoanProfessionPop professionPop;//贷款身份排序
    private LoanSortPop sortPop;//贷款排序
    private LoanAmountPop amountPop;//贷款金额
    private LoanTypePop typePop;//贷款类型
    private LoanPopFilterList filterList;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId= Self.Page.app_loan_list_page;

        ViewGroup.LayoutParams params = xBanner.getLayoutParams();
        int width = ScreenUtil.getScreenWidth(mContext);
        params.height = (int) (width * 28 / 75.0f);
        xBanner.setLayoutParams(params);
        xBanner.setmAutoPalyTime(Constant.BANNER_INTERVAL_TIME);

        data = new ArrayList<>();
        adapter = new LoanFilterProductAdapter(mContext, data);

        adapter.setBuriedInfo(mEnterPageTime,mCurrentPageId,mPrePageId);

        final LinearLayoutManager layoutManager=new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (layoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
                        appBarLayout.setExpanded(true, true);
                    }
                }
            }
        });

        footerLoadMore.setStateNoMoreDataStr("有借有还，再借不难");
        srLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageNumber++;
                loadProducts(pageNumber, codes, order, amount);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNumber = PAGE_START;
                loadProducts(pageNumber, codes, order, amount);
            }
        });

        expansionDownDrawable = ContextCompat.getDrawable(mContext, R.mipmap.icon_expansion_down);
        expansionUpDrawable = ContextCompat.getDrawable(mContext, R.mipmap.icon_expansion_up_yellow);

        Intent intent = getIntent();
        codes = intent.getStringExtra(LOAN_TYPE_AUTH_REPAYMENT_CODE_S);
        codes = (codes == null ? "" : codes);
        crowds_code = intent.getStringExtra(LOAN_FILTER_PROFESSION_S);
        crowds_code = (crowds_code == null) ? "" : crowds_code;
        amount = intent.getIntExtra(LOAN_FILTER_AMOUNT_I, 0);
        if (amount > 0) {
            tvAmount.setText(String.format(Locale.CHINESE, "%.1f", amount / 10000f) + "万");
        }
        String identityName = intent.getStringExtra(LOAN_FILTER_PROFESSION_NAME_S);
        if (!TextUtils.isEmpty(identityName)) {
            tvIdentity.setText(identityName);
        }
        String authTypeName = intent.getStringExtra(LOAN_TYPE_AUTH_REPAYMENT_NAME_S);
        if (!TextUtils.isEmpty(authTypeName)) {
            tvType.setText(authTypeName);
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        loadBannerData();
        loadProducts(pageNumber, codes, order, amount);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_loan_filter;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (xBanner.getParent() != null) {
            xBanner.startAutoPlay();
        }
        GoogleAnalyticsUtil.setScreenName(Google.LOANS_PRODUCT);
        UmengEventUtils.pageEvent(mContext,getString(R.string.event_0x04e));
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (xBanner.getParent() != null) {
            xBanner.stopAutoPlay();
        }
    }

    @OnClick({R.id.rl_sort_filter, R.id.ll_identity_filter,
            R.id.ll_amount_filter, R.id.ll_type_filter})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_sort_filter:
                //选择排序方式
                showSortPop();
                break;
            case R.id.ll_identity_filter:
                //选择身份
                dismissAmountPop();
                dismissTypePop();
                tvIdentity.setTextColor(COLOR_SELECTED);
                tvIdentity.setCompoundDrawablesWithIntrinsicBounds(null, null, expansionUpDrawable, null);
                if (filterList == null) {
                    loadPopData(POP_PROFESSION);
                } else {
                    showProfessionPop();
                }
                break;
            case R.id.ll_amount_filter:
                //贷款金额
                dismissProfessionPop();
                dismissTypePop();
                tvAmount.setTextColor(COLOR_SELECTED);
                tvAmount.setCompoundDrawablesWithIntrinsicBounds(null, null, expansionUpDrawable, null);
                showAmountPop();
                break;
            case R.id.ll_type_filter:
                //贷款类型、还款方式
                dismissProfessionPop();
                dismissAmountPop();
                tvType.setTextColor(COLOR_SELECTED);
                tvType.setCompoundDrawablesWithIntrinsicBounds(null, null, expansionUpDrawable, null);
                if (filterList == null) {
                    loadPopData(POP_AUTH_REPAYMENT);
                } else {
                    showTypePop();
                }
                break;
        }
    }

    /**
     * 计算整个排序pop的高度
     */
    private int calculateSortPopHeight() {
        int halfHeight = (int) (ScreenUtil.getScreenHeight(mContext) * 0.5f);
        int[] positionTitleBar = new int[2];
        titleBar.getLocationOnScreen(positionTitleBar);
        int[] positionSortFilterPosition = new int[2];
        rlSortFilter.getLocationOnScreen(positionSortFilterPosition);
        int height = positionSortFilterPosition[1] + rlSortFilter.getHeight() -
                positionTitleBar[1] - titleBar.getHeight();
        return Math.max(halfHeight, height);
    }

    /**
     * 计算条件筛选[贷款身份、金额、类型]整个pop的高度
     */
    private int calculateConditionPopHeight() {
        int halfHeight = (int) (ScreenUtil.getScreenHeight(mContext) * 0.5f);
        int[] positionTitleBar = new int[2];
        llContainer.getLocationOnScreen(positionTitleBar);
        int[] positionSortFilterPosition = new int[2];
        rlSortFilter.getLocationOnScreen(positionSortFilterPosition);
        int height = positionSortFilterPosition[1] + rlSortFilter.getHeight() -
                positionTitleBar[1] - llContainer.getHeight();
        return Math.max(halfHeight, height);
    }

    /**
     * 获取条件筛选[贷款身份、金额、类型]显示pop的y坐标
     */
    private int getShowPositionY() {
        int[] position = new int[2];
        llContainer.getLocationOnScreen(position);
        return position[1] + llContainer.getHeight();
    }

    /**
     * 处理筛选条件codes
     */
    private void handlerFilterCodes() {
        List<String> list = new ArrayList<>();
        if (loanPopFilters != null && loanPopFilters.size() > 0) {
            for (int i = 0, size = loanPopFilters.size(); i < size; i++) {
                list.add(loanPopFilters.get(i).getCode());
            }
        }
        if (repaymentFilters != null && repaymentFilters.size() > 0) {
            for (int i = 0, size = repaymentFilters.size(); i < size; i++) {
                list.add(repaymentFilters.get(i).getCode());
            }
        }
        //拼接codes
        StringBuilder sb = new StringBuilder();
        if (list.size() > 0) {
            for (int i = 0, size = list.size(); i < size; i++) {
                sb.append(list.get(i));
                //加","
                if (i != size - 1) {
                    sb.append(",");
                }
            }
        }
        codes = sb.toString();
    }

    /**
     * 显示贷款排序pop
     */
    private void showSortPop() {
        if (sortPop == null) {
            sortPop = new LoanSortPop(mContext);
            sortPop.setLoanSortEnsuredListener(new LoanSortPop.LoanSortEnsuredListener() {
                @Override
                public void onLoanSortEnsured(String sort) {
                    showProgressDialog(false);
                    order = sort;
                    if(Constant.LOAN_LIMIT.equals(sort)){
                        //额度由高到低
                        SelfUtils.buriedClickData(Self.Action.app_click_loan_filter_quota_desc,
                                Self.Action.app_click_loan_filter_quota_desc_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                    }else if(Constant.LOAN_SPEED.equals(sort)){
                        //速度由快到慢
                        SelfUtils.buriedClickData(Self.Action.app_click_loan_filter_velocity_desc,
                                Self.Action.app_click_loan_filter_velocity_desc_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                    }else if(Constant.LOAN_RATE.equals(sort)){
                        //费率由低到高
                        SelfUtils.buriedClickData(Self.Action.app_click_loan_filter_rate_asc,
                                Self.Action.app_click_loan_filter_rate_asc_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                    }else if(Constant.LOAN_APPR.equals(sort)){
                        //批核速度由快到慢
                        SelfUtils.buriedClickData(Self.Action.app_click_loan_filter_approved_desc,
                                Self.Action.app_click_loan_filter_approved_desc_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                    }
                    pageNumber = PAGE_START;
                    loadProducts(pageNumber, codes, order, amount);
                }
            });
        }
        if (!sortPop.isShowing()) {
            sortPop.setHeight(calculateSortPopHeight());
            sortPop.setPopCurrent(order);
            sortPop.showAtLocation(rlSortFilter, Gravity.BOTTOM, 0, 0);
        }
    }

    /**
     * 显示贷款身份pop
     */
    private void showProfessionPop() {
        if (professionPop == null) {
            professionPop = new LoanProfessionPop(mContext, filterList.getCrowd_list());
            professionPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    tvIdentity.setTextColor(COLOR_NORMAL);
                    tvIdentity.setCompoundDrawablesWithIntrinsicBounds(null, null, expansionDownDrawable, null);
                }
            });
            professionPop.setLoanProfessionEnsuredListener(new LoanProfessionPop.LoanProfessionEnsuredListener() {
                @Override
                public void onLoanProfessionEnsured(LoanPopFilterList.LoanPopFilter itemBean) {
                    SelfUtils.buriedClickData(Self.Action.app_click_loan_filter_crowd,
                            Self.Action.app_click_loan_filter_crowd_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    showProgressDialog(false);
                    tvIdentity.setText(itemBean.getName());
                    crowds_code = itemBean.getCode();
                    pageNumber = PAGE_START;
                    loadProducts(pageNumber, codes, order, amount);
                }
            });
        }
        if (!professionPop.isShowing()) {
            professionPop.setHeight(calculateConditionPopHeight());
            professionPop.setCurrentSelected(crowds_code);
            professionPop.showAtLocation(llContainer, Gravity.NO_GRAVITY, 0, getShowPositionY());
        }
    }

    /**
     * 隐藏贷款身份pop
     */
    private void dismissProfessionPop() {
        if (professionPop != null && professionPop.isShowing()) {
            professionPop.dismiss();
        }
    }

    private void showAmountPop() {
        if (amountPop == null) {
            amountPop = new LoanAmountPop(mContext);
            amountPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    tvAmount.setTextColor(COLOR_NORMAL);
                    tvAmount.setCompoundDrawablesWithIntrinsicBounds(null, null, expansionDownDrawable, null);
                }
            });
            amountPop.setLoanAmountEnsuredListener(new LoanAmountPop.LoanAmountEnsuredListener() {
                @Override
                public void onLoanAmountEnsured(int ensuredAmount) {
                    SelfUtils.buriedClickData(Self.Action.app_click_loan_filter_amount,
                            Self.Action.app_click_loan_filter_amount_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    showProgressDialog(false);
                    pageNumber = PAGE_START;
                    amount = ensuredAmount;
                    if (amount == 0) {
                        tvAmount.setText("金额不限");
                    } else {
                        float temp = amount / 10000.0f;
                        tvAmount.setText(String.format(Locale.CHINESE, "%.1f", temp) + "万");
                    }
                    loadProducts(pageNumber, codes, order, amount);
                }
            });
        }
        if (!amountPop.isShowing()) {
            amountPop.setHeight(calculateConditionPopHeight());
            amountPop.setCurrent(amount);
            amountPop.showAtLocation(llContainer, Gravity.NO_GRAVITY, 0, getShowPositionY());
        }
    }

    private void dismissAmountPop() {
        if (amountPop != null && amountPop.isShowing()) {
            amountPop.dismiss();
        }
    }

    /**
     * 显示贷款类型pop
     */
    private void showTypePop() {
        if (typePop == null) {
            typePop = new LoanTypePop(mContext, filterList.getAuth_list(), filterList.getRepayment_list());
            typePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    tvType.setTextColor(COLOR_NORMAL);
                    tvType.setCompoundDrawablesWithIntrinsicBounds(null, null, expansionDownDrawable, null);
                }
            });
            typePop.setLoanTypeEnsuredListener(new LoanTypePop.LoanTypeEnsuredListener() {
                @Override
                public void onLoanTypeEnsured(List<LoanPopFilterList.LoanPopFilter> authTypeSelects,
                                              List<LoanPopFilterList.LoanPopFilter> repaymentSelects) {
                    SelfUtils.buriedClickData(Self.Action.app_click_loan_filter_type,
                            Self.Action.app_click_loan_filter_type_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    showProgressDialog(false);
                    if (authTypeSelects.size() == 1) {
                        tvType.setText(authTypeSelects.get(0).getName());
                    } else {
                        tvType.setText("借款类型");
                    }
                    loanPopFilters = authTypeSelects;
                    repaymentFilters = repaymentSelects;
                    handlerFilterCodes();
                    pageNumber = PAGE_START;
                    loadProducts(pageNumber, codes, order, amount);
                }
            });
        }
        if (!typePop.isShowing()) {
            typePop.setHeight(calculateConditionPopHeight());
            if (!TextUtils.isEmpty(codes)) {
                String[] selects = codes.split(",");
                if (loanPopFilters == null) {
                    loanPopFilters = new ArrayList<>();
                }
                List<LoanPopFilterList.LoanPopFilter> temp = filterList.getAuth_list();
                LoanPopFilterList.LoanPopFilter t;
                for (int i = 0, size = selects.length; i < size; i++) {
                    for (int j = 0, jSize = temp.size(); j < jSize; j++) {
                        t = temp.get(j);
                        if (t.getCode().equals(selects[i]) && !loanPopFilters.contains(t)) {
                            loanPopFilters.add(t);
                            break;
                        }
                    }
                }
            }
            typePop.setCurrentSelects(loanPopFilters, repaymentFilters);
            typePop.showAtLocation(llContainer, Gravity.NO_GRAVITY, 0, getShowPositionY());
        }
    }

    /**
     * 隐藏贷款类型pop
     */
    private void dismissTypePop() {
        if (typePop != null && typePop.isShowing()) {
            typePop.dismiss();
        }
    }

    private void loadBannerData() {
        Observable<String> observable= Api.getBannerData(Constant.GLB0320);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                hideBanner();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                BannerResult bannerResult = JsonUtil.json2Object(s, BannerResult.class);
                if (bannerResult.getCode() == Constant.SUC_CODE) {
                    if (bannerResult.getData() != null) {
                        final List<Banner.CarouselFigureListBean> data =
                                bannerResult.getData().getCarousel_figure_list();
                        if (data != null && data.size() > 0) {
                            xBanner.stopAutoPlay();
                            xBanner.setData(data, null);
                            xBanner.setmAdapter(new XBanner.XBannerAdapter() {
                                @Override
                                public void loadBanner(XBanner banner, Object model, View view, int position) {
                                    ImageLoaderUtil.displayImageWithPlaceHolder(URLUtil.CBB_IMG_URL + ((Banner.CarouselFigureListBean) model).getImage(),
                                            (ImageView) view,
                                            R.mipmap.img_default_banner);
                                }
                            });
                            xBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                                @Override
                                public void onItemClick(XBanner banner, int position) {
                                    SelfUtils.buriedClickData(Self.Action.app_click_loan_filter_top_banner,
                                            Self.Action.app_click_loan_filter_top_banner_des,
                                            mEnterPageTime,
                                            mCurrentPageId,
                                            mPrePageId);
                                    Banner.CarouselFigureListBean bean = data.get(position);
                                    CommonJumpController controller = new CommonJumpController(mContext);
                                    Map<String, Object> extra = new HashMap<>();
                                    extra.put(CommonJumpController.FROM_PAGE, "贷款-人群分类-banner");
                                    extra.put(EventWebViewActivity.WEB_TYPE_I, 33);
                                    controller.bannerJump(bean, extra);
                                }
                            });
                            xBanner.startAutoPlay();
                        } else {
                            hideBanner();
                        }
                    } else {
                        hideBanner();
                    }
                } else {
                    hideBanner();
                    ToastUtil.showToast(bannerResult.getMsg());
                }
            }
        });
    }

    private void hideBanner() {
        toolbarLayout.removeView(xBanner);
        appBarLayout.removeView(toolbarLayout);
    }

    /**
     * 加载筛选数据
     *
     * @param popToShow 1、身份pop 2借款类型pop
     */
    private void loadPopData(final int popToShow) {
        showProgressDialog(false);
        Observable<String> observable=Api.getLoanPopFilter();
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                dismissProgressDialog();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                LoanPopFilterListResult listResult =
                        JsonUtil.json2Object(s, LoanPopFilterListResult.class);
                if (listResult != null) {
                    if (listResult.getCode() == Constant.SUC_CODE) {
                        if (listResult.getData() != null) {
                            filterList = listResult.getData();
                            //贷款身份加入一项为 “身份不限”
                            LoanPopFilterList.LoanPopFilter unLimit =
                                    new LoanPopFilterList.LoanPopFilter();
                            unLimit.setCode("");
                            unLimit.setName("身份不限");
                            listResult.getData().getCrowd_list().add(0, unLimit);

                            if (popToShow == POP_PROFESSION) {
                                showProfessionPop();
                            }
                            if (popToShow == POP_AUTH_REPAYMENT) {
                                showTypePop();
                            }
                        }
                    } else {
                        ToastUtil.showToast(listResult.getMsg());
                    }
                }
            }
        });
    }

    private void loadProducts(int page, String codes, String order, int amount) {
        Map<String,Object> params = new HashMap<>();
        params.put("index", String.valueOf(page));
        if (!TextUtils.isEmpty(codes)) {
            params.put("codes", codes);
        }
        if (!TextUtils.isEmpty(crowds_code)) {
            params.put("crowds_code", crowds_code);
        }
        if (!TextUtils.isEmpty(order)) {
            params.put("order", order);
        }
        if (amount > 0) {
            params.put("amount", String.valueOf(amount));
        }
        String cityName = LocationUtil.getCityName();
        if (!TextUtils.isEmpty(cityName)) {
            params.put("city", cityName);
        }
        Observable<String> observable=Api.getLoanFilterData(params);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                dismissProgressDialog();
                if (recyclerView.getAdapter() == null) {
                    recyclerView.setAdapter(adapter);
                }
                srLayout.finishRefresh();
                srLayout.finishLoadmore();
                if (pageNumber < speedOrProductResult.getPage().getTotalPage()) {
                    footerLoadMore.setStatePreLoading();
                    srLayout.setLoadmoreFinished(false);
                } else {
                    //无更多数据
                    footerLoadMore.setStateNoMoreData();
                    footerLoadMore.setNoMoreDataIcon(R.mipmap.icon_loan);
                    srLayout.setLoadmoreFinished(true);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                handlePageWhenFailure();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
                if (recyclerView.getAdapter() == null) {
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onNext(String s) {
                speedOrProductResult = JsonUtil.json2Object(s, SpeedOrProductResult.class);
                if (speedOrProductResult != null) {
                    if (speedOrProductResult.getCode() == Constant.SUC_CODE) {
                        if (speedOrProductResult.getData() != null) {
                            if (pageNumber == PAGE_START) {
                                data.clear();
                            }
                            data.addAll(speedOrProductResult.getData().getLoan_list());
                            adapter.notifyDataSetChanged();
                            if (pageNumber == PAGE_START) {
                                recyclerView.smoothScrollToPosition(0);
                            }
                        }
                    } else {
                        handlePageWhenFailure();
                        ToastUtil.showToast(speedOrProductResult.getMsg());
                    }
                }
            }
        });
    }

    private void handlePageWhenFailure() {
        //加载出错时，处理分页
        pageNumber--;
        if (pageNumber < PAGE_START) {
            pageNumber = PAGE_START;
        }
    }
}
